package com.zhanghu.backendZray.manager.user;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.zhanghu.backendZray.cache.LoginTokenCache;
import com.zhanghu.backendZray.cache.UserCache;
import com.zhanghu.backendZray.cache.UserMenuCache;
import com.zhanghu.backendZray.manager.role.UserRoleMenuManager;
import com.zhanghu.backendZray.pojo.dto.UserTokenInfo;
import com.zhanghu.backendZray.pojo.entity.User;
import com.zhanghu.backendZray.service.UserOnlineTokenService;
import com.zhanghu.backendZray.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author ZhangDong
 * @date 2024/9/6 10:00
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class UserCacheManager {
    private final UserOnlineTokenService userOnlineTokenService;
    private final UserService userService;
    private final UserRoleMenuManager userRoleMenuManager;

    @PostConstruct
    public void initTokenCache() {
        List<UserTokenInfo> list = userOnlineTokenService.listUserTokenNoExpire2TokenInfo();
        log.info("程序启动, 初始化token数据, list:{}", JSON.toJSONString(list));
        for (UserTokenInfo tokenInfo : list) {
            LoginTokenCache.putTokenInfo(tokenInfo.getLoginToken(), tokenInfo);
        }
        log.info("程序启动, 初始化token数据, 结束...");
    }

    @PostConstruct
    public void initUserCache() {
        List<User> list = userService.list();
        log.info("程序启动, 初始化所有用户数据(包含菜单), list:{}", JSON.toJSONString(list));
        for (User user : list) {
            UserCache.putUser(user);
            Integer userId = user.getId();
            List<String> menuList = userRoleMenuManager.currentUserMenu(userId);
            if (CollUtil.isNotEmpty(menuList)) {
                UserMenuCache.putMenu(userId, menuList);
            }
        }
        log.info("程序启动, 初始化所有用户数据(包含菜单), 结束...");
    }
}
